package com.norrielm.GooglePlusPosts;

import android.app.Activity;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import com.norrielm.GooglePlusPosts.models.PostAdapter;
import com.norrielm.GooglePlusPosts.models.Receiver;
import com.norrielm.GooglePlusPosts.service.ProfileReceiver;
import com.norrielm.GooglePlusPosts.service.SensorDataSender;
import com.norrielm.GooglePlusPosts.service.ServerReceiver;

/**
 * Controller of content to be displayed in the view.
 * 
 * @author Lauren Norrie (norrielm)
 */
public class GooglePlusPosts extends Activity {

	private static final String LOG = "GooglePlusPosts";
	private GooglePlusPresenter gplus;
	private ServerReceiver serverReceiver;
	private ProfileReceiver profileReceiver;
	private SensorDataSender sender;
	
	private final Receiver<String> logger = new Receiver<String>() {
		@Override public void accept(String t) {
		  Log.d(LOG, t);
		}
	};	
	private final Receiver<String> gplusUpdate = new Receiver<String>() {
		@Override public void accept(String id) {
			gplus.updateFeedWithUser(id);
			logger.accept("Feed updated with id " + id);
		}
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		// Set up the ListView with an adapter.
		ListView listView = (ListView) findViewById(R.id.ListView);
		PostAdapter adapter = new PostAdapter(this);
		listView.setAdapter(adapter);
		listView.setTextFilterEnabled(true);
		
		gplus = new GooglePlusPresenter(logger, adapter);
		gplusUpdate.accept(ServerReceiver.TEST_ID); 
		
		// TODO(norrielm): Get profile ID from device - ask on start up?
		String deviceId = "109691107925034413137"; // Lauren's g+ (for testing)
		SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);		
		sender = new SensorDataSender(this, sm, ServerReceiver.HOST, ServerReceiver.PORT, deviceId);
		
		serverReceiver = new ServerReceiver(); 
		profileReceiver = new ProfileReceiver(this, gplusUpdate);
	}

	@Override
    protected void onResume() {
        super.onStart();
        if (sender != null) {
        	sender.onResume();
        } 
    }
	
	@Override
    protected void onDestroy() {
        profileReceiver.destroy();
        serverReceiver.stop();
        super.onDestroy();
    }
	
	@Override
    protected void onStop() {
		sender.onResume();
        super.onStop();
    }
}
